<template>
  <el-card class="app-container">
    <div>
      <div class="itemTitle">试题库管理</div>
      <div class="search">
    <el-form :inline="true" :model="queryParams" ref="queryForm">
<el-col :span="5">
      <el-form-item label="题目类型" prop="type">
        <el-select 
         @change="handleQuery"
                v-model="queryParams.type" placeholder="请选择类型" clearable>
              <el-option
                v-for="dict in testTypeList"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
      </el-form-item>
</el-col>
<el-col :span="5">
      <el-form-item label="题干关键词" prop="stem">
        <el-input
          v-model="queryParams.stem"
          placeholder="请输入题干"
          clearable
        />
      </el-form-item>
</el-col>

      <el-col :span="5">
      <el-form-item>
        <el-button type="primary"  @click="handleQuery">搜索</el-button>
        <el-button  @click="resetQuery">重置</el-button>
      </el-form-item>
      </el-col>
    </el-form>
      </div>
      <div class="content">
        <div class="ct-btns">
          <el-button type="primary" @click="handleAdd" v-hasPermi="['edu:itembank:add']">新增</el-button>
          <!-- <el-button type="primary" @click="handleAddByDialog" v-hasPermi="['edu:itembank:add']">弹窗新增</el-button>
          <el-button type="success" @click="handleImport" v-hasPermi="['edu:itembank:import']">批量导入</el-button>
          <el-button type="warning"  @click="handleExport" v-hasPermi="['edu:itembank:export']">批量导出</el-button>
          <el-button type="warning"  @click="importTemplate" v-hasPermi="['edu:itembank:downImportTemplate']">下载导入模板</el-button> -->
        </div>
        <div class="ct-table">
          <elTables
              :table-data="tableData"
              :columns="tableColumns"
              :totalLength="total"
              :currentPage="queryParams.pageNum"
              :handle-current-change="handleCurrentChange"
              isPagin
              :curHeight="tableHeight"
          />
        </div>
      </div>
      </div>
    <!-- 添加或修改试题库对话框 -->
    <el-dialog :title="title" :visible.sync="open"  append-to-body @close="cancel" class="dialog-form">
      <!-- <p class="title-level2">二级标题可选</p> -->
      <el-form  ref="form" :model="form" :rules="rules" label-width="140px">
        <el-row>


        <el-col :span="12">
          <el-form-item label="题目类型" prop="type">
            <el-select 
                v-model="form.type" placeholder="请选择类型" :readonly="!isEdit" :disabled="!isEdit">
              <el-option
                v-for="dict in testTypeList"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="所属科目" prop="subject">
              <el-select 
                v-model="form.subject" placeholder="请选择类型" :readonly="!isEdit" :disabled="!isEdit">
              <el-option
                v-for="dict in courseSubjectList"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
                </el-form-item>
        </el-col>
        
        <!-- <el-col :span="12">
          <el-form-item label="难度" prop="level">
            <el-radio-group v-model="form.level" :readonly="!isEdit" :disabled="!isEdit">
              <el-radio label="1">简单</el-radio>
              <el-radio label="2">一般</el-radio>
              <el-radio label="3">困难</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="题干" prop="stem">
            <el-input v-model="form.stem" type="textarea" placeholder="请输入题干" :readonly="!isEdit" :disabled="!isEdit"/>
          </el-form-item>
        </el-col> -->

        <!-- <el-col :span="24">
          <el-form-item label="选项" prop="stem">  </el-form-item>
        </el-col>


        <el-col :span="12">
          <el-form-item label="正确答案 " prop="answer">
            <el-input v-model="form.answer" placeholder="请输入正确答案 " :readonly="!isEdit" :disabled="!isEdit"/>
          </el-form-item>
        </el-col> -->
      </el-row>
      </el-form>
      <!-- 单选 -->
      <ztextDX
        @formData="formData"
        :isEdit="isEdit"
        ref="ztextDX"
        v-if="form.type == '1'"
      ></ztextDX>

      <!-- 判断 -->
      <ztextPD
        @formData="formData"
        :isEdit="isEdit"
        ref="ztextPD"
        v-if="form.type == '2'"
      ></ztextPD>


      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="continueSave">保存并继续添加</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
    <!-- 导入 -->
    <el-dialog
        :title="upload.title"
        :visible.sync="upload.open"
        width="800px"
        append-to-body
    >
      <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="upload.open = false">取消</el-button>
        <el-button type="primary" @click="submitFileForm">确定</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
  const defaultQueryParams = {
    pageNum: 1,
    pageSize: 10,
  };
  import { getToken } from "@/utils/auth";
import { pageItembank,listItembank, getItembank, delItembank, addItembank, updateItembank, exportItembank ,downImportTemplate} from "@/api/edu/testQuestionsManagement";
import ztextDX from "../components/ztextDX";//单选题组件
import ztextPD from "../components/ztextPD";//判断题组件

export default {
  name: "Itembank",
  components:{ztextDX,ztextPD},
  data() {
    return {
      tableHeight:0,
      isEdit:false,
      dialogFormVisible:false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url:
            process.env.VUE_APP_BASE_API + "/edu/itembank/importData",
      },
      tableData: [],
      // 查询参数
      queryParams: {
        ...defaultQueryParams,

        type: null,
        stem: null,
        factoryId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        type: [
          { required: true, message: "类型不能为空", trigger: "change" }
        ],
        subject: [
          { required: true, message: "科目不能为空", trigger: "change" }
        ],
        options: [
          { required: true, message: "选项不能为空", trigger: "blur" }
        ],
        level: [
          { required: true, message: "难度不能为空", trigger: "blur" }
        ],
        stem: [
          { required: true, message: "题干不能为空", trigger: "blur" }
        ],
        answer: [
          { required: true, message: "正确答案 不能为空", trigger: "blur" }
        ],
      },
      tableColumns: [
        { key:"stem",title:"题干"},
        { key:"subject",title:"所属科目",
        render: (h, params) => {
            return h("div", [
              h(
                "span",
                this.selectDictLabel(this.courseSubjectList, params.row.subject)
              ),
            ]);
          },},
      { key:"type",title:"难度",
      render: (h, params) => {
            return h("div", [
              h(
                "span",
                this.selectDictLabel(this.nanduList, params.row.subject)
              ),
            ]);
          },},
      { key:"type",title:"类型",
      render: (h, params) => {
            return h("div", [
              h(
                "span",
                this.selectDictLabel(this.testTypeList, params.row.type)
              ),
            ]);
          }},
      
          { key:"createTime",title:"创建时间"},
      
            {
          title: "操作",
          align: "center",
          fixed:'right',
          width: 200,
          render: (h, params) => {
            return h("div", [
              h(
                  "el-button",
                  {
                    props: {
                      type: "text",
                      size: "small",
                    },
                    directives: [
                      {
                        name: "hasPermi",
                        value: ["edu:itembank:edit"],
                      },
                    ],
                    on: {
                      click: () => {
                        this.handleUpdate(params.row,1);
                      },
                    },
                  },
                  "编辑"
              ),
              h(
                  "el-button",
                  {
                    props: {
                      type: "text",
                      size: "small",
                    },
                    directives: [
                      {
                        name: "hasPermi",
                        value: ["edu:itembank:info"],
                      },
                    ],
                    on: {
                      click: () => {
                        this.handleUpdate(params.row,2)
                      },
                    },
                  },
                  "查看"
              ),
              h(
                  "el-button",
                  {
                    props: {
                      type: "text",
                      size: "small",
                    },
                    directives: [
                      {
                        name: "hasPermi",
                        value: ["edu:itembank:remove"],
                      },
                    ],
                    on: {
                      click: () => {
                        this.handleDelete(params.row)
                      },
                    },
                  },
                  "删除"
              ),
            ]);
          },
        },
      ],
      testTypeList:[],
      courseSubjectList:[],
      nanduList:[]

    };
  },
  created() {
    this.getPage();

    // 获取试题类型列表
    this.getDicts("test_type").then(response => {
      this.testTypeList = response.data;
    });

    // 获取所属科目
    this.getDicts("course_subject").then(response => {
      this.courseSubjectList = response.data;
    });
        // 获取难度
    this.getDicts("test_difficulty").then(response => {
      this.nanduList = response.data;
    });
  },
  mounted(){
    this.$nextTick(() => {
      this.getTableHeight();
    })
  },
  methods: {
    formData(val) {
      this.form = { ...this.form, ...val }
    },
    /** 下载模板操作 */
    importTemplate() {
      downImportTemplate().then((response) => {
        this.download(response.msg);
      });
    },
    handleAddByDialog(){
      this.dialogFormVisible=true;
    },
    getTableHeight(){
      let height=document.getElementsByClassName('ct-table')[0].clientHeight;
      this.tableHeight= height - 40;
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getPage();
    },
    /** 查询试题库列表 */
    getPage() {
      this.loading = true;
      pageItembank(this.queryParams).then(response => {
        this.tableData = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        type: this.testTypeList[0].dictValue,
        subject: null,
        options: null,
        level: null,
        stem: null,
        answer: null,
        factoryId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        createDept: null,
        delFlag: null
      };
      this.$nextTick(()=>{
        this.$refs.ztextDX.reset();
      })

      this.resetForm("form");
      
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getPage();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isEdit= true;
      this.title = "新增题目";
    },
    /** 修改按钮操作 */
    handleUpdate(row,type) {
        if(type==1){
          this.isEdit=true;
          this.title = "编辑题目";
        }else{
          this.isEdit=false;
          this.title = "查看题目";
        }
      this.reset();
      const id = row.id || this.ids
      getItembank(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.$nextTick(() => {
          if (row.type == "1") {
            // let options = JSON.parse(this.form.options)
            this.form.options = JSON.parse(this.form.options)
            this.$refs.ztextDX.form = { ...this.form }
          } else if (row.type == "2") {
            this.$refs.ztextPD.form = row
          } else if (row.type == "5") {
            let ls = (row.answer.split(",") ?? []).map((_) => {
              let obj = {}
              obj.value = _
              return obj
            })
            let formParams = {
              ...row,
              domains: ls,
            }
            this.$refs.ztextTK.form = formParams
          } else if (row.topicType == "4") {
            this.$refs.ztextJD.form = row
          }
        })
      });
    },
    // /** 提交按钮 */
    // submitForm() {
    //   this.$refs["form"].validate(valid => {
    //     if (valid) {
    //       if (this.form.id != null) {
    //         updateItembank(this.form).then(response => {
    //           this.msgSuccess("修改成功");
    //           this.open = false;
    //           this.getPage();
    //         });
    //       } else {
    //         addItembank(this.form).then(response => {
    //           this.msgSuccess("新增成功");
    //           this.open = false;
    //           this.getPage();
    //         });
    //       }
    //     }
    //   });
    // },

        // 确定
    submitForm() {
      this.form.options = JSON.stringify(this.form.options)
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return
        } else if (valid) {
          if (this.form.type == "1") {
            this.$refs.ztextDX.$refs.form.validate((valid) => {
              if (!valid) {
                return
              } else {
                addItembank(this.form).then((res) => {
                  if (res.code == 200) {
                    this.$message.success("保存成功")
                    this.getPage();
                    this.open = false;
                    this.$refs.ztextDX.reset()
                  } else {
                    this.$message.error(res.data.msg)
                  }
                })
              }
            })
          } else if (this.form.type == "2") {
            this.$refs.ztextPD.$refs.form.validate((valid) => {
              if (!valid) {
                return
              } else {
                addItembank(this.form).then((res) => {
                  if (res.code == 200) {
                    this.$message.success("保存成功")
                    this.getPage();
                    this.open = false;
                    this.$refs.ztextPD.reset()
                  } else {
                    this.$message.error(res.data.msg)
                  }
                })
              }
            })
          } else if (this.form.type == "4") {
            // 简答题
            this.$refs.ztextJD.$refs.form.validate((valid) => {
              if (!valid) {
                return
              } else {
                addItembank(this.form).then((res) => {
                  if (res.code == 200) {
                    this.$message.success("保存成功")
                    this.getPage();
                    this.open = false;
                    this.$refs.ztextJD.reset()
                  } else {
                    this.$message.error(res.data.msg)
                  }
                })
              }
            })
          } else if (this.form.type == "5") {
            // 填空题
            let answerList = []
            this.form.domains.map((_) => {
              answerList.push(_.value)
            })
            let params = {
              ...this.form,
              answerNum: this.form.domains.length ?? 1,
              answer: answerList.join(","),
            }
            addItembank(params).then((res) => {
              if (res.code == 200) {
                this.$message.success("保存成功")
                this.getPage();
                this.$refs.ztextTK.reset()
              } else {
                this.$message.error(res.data.msg)
              }
            })
          }
        }
      })
    },

    // 保存并继续试题
    continueSave() {
      this.form.options = JSON.stringify(this.form.options)
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return
        } else if (valid) {
          if (this.form.type == "1") {
            this.$refs.ztextDX.$refs.form.validate((valid) => {
              if (!valid) {
                return
              } else {
                addItembank(this.form).then((res) => {
                  if (res.code == 200) {
                    this.$message.success("保存成功")
                    this.getPage();
                    this.$refs.ztextDX.reset()
                  } else {
                    this.$message.error(res.data.msg)
                  }
                })
              }
            })
          } else if (this.form.type == "2") {
            this.$refs.ztextPD.$refs.form.validate((valid) => {
              if (!valid) {
                return
              } else {
                addItembank(this.form).then((res) => {
                  if (res.code == 200) {
                    this.$message.success("保存成功")
                    this.getPage();
                    this.$refs.ztextPD.reset()
                  } else {
                    this.$message.error(res.data.msg)
                  }
                })
              }
            })
          } else if (this.form.type == "4") {
            // 简答题
            this.$refs.ztextJD.$refs.form.validate((valid) => {
              if (!valid) {
                return
              } else {
                addItembank(this.form).then((res) => {
                  if (res.code == 200) {
                    this.$message.success("保存成功")
                    this.getPage();
                    this.$refs.ztextJD.reset()
                  } else {
                    this.$message.error(res.data.msg)
                  }
                })
              }
            })
          } else if (this.form.type == "5") {
            // 填空题
            let answerList = []
            this.form.domains.map((_) => {
              answerList.push(_.value)
            })
            let params = {
              ...this.form,
              answerNum: this.form.domains.length ?? 1,
              answer: answerList.join(","),
            }
            addItembank(params).then((res) => {
              if (res.code == 200) {
                this.$message.success("保存成功")
                this.getPage();
                this.$refs.ztextTK.reset()
              } else {
                this.$message.error(res.data.msg)
              }
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
            let data
            if(Array.isArray(ids)){
              data=ids
            }else{
              data=[ids]
            }
          return delItembank(data);
        }).then(() => {
          this.getPage();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有试题库数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportItembank(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getPage();
    },
    // 提交导入文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  }
};
</script>
<style lang="scss" scoped>

</style>
